package com.proton.carepatchtemp.fragment;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.adapter.ReportListAdapter;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.base.BaseFragment;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.database.table.Report;
import com.proton.carepatchtemp.utils.NetUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.ReportCenter;
import com.sdsmdg.tastytoast.TastyToast;
import com.sinping.iosdialog.animation.BaseAnimatorSet;
import com.sinping.iosdialog.animation.BounceEnter.BounceTopEnter;
import com.sinping.iosdialog.animation.SlideExit.SlideBottomExit;
import com.sinping.iosdialog.dialog.widget.NormalDialog;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

public class ReportListFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate {

    public boolean isCheckAll = false;
    ReportListAdapter mReportListAdapter;
    LinearLayoutManager mLinearLayoutManager;
    ArrayList<Report> data = new ArrayList<>();
    Set<Report> deleteReports = new HashSet<>();
    RecyclerView mRcvReportList;
    BGARefreshLayout mBgaRflReport;
    int i = 0;
    private BaseAnimatorSet bas_in;
    private BaseAnimatorSet bas_out;
    //0是全部  1为收藏
    private int isCollect = 0;
    private LinearLayout mLnlNullReport;
    private BGANormalRefreshViewHolder mBGANormalRefreshViewHolder;
    /**
     * 删除
     */
    private TextView mTvDeleteAllChecked;
    /**
     * 全选
     */
    private TextView mTvSelectAll;
    private LinearLayout mLlyMenu;
    /**
     * 您还没有任何报告！赶紧去测量吧！
     */
    private TextView mTvNullReport;
    /**
     * 重试
     */
    private TextView mTvNoNetRetry;
    private LinearLayout mLnlReportNoNet;

    public ReportListFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReportListAdapter = new ReportListAdapter(getActivity(), data, getChildFragmentManager());
        mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);

        bas_in = new BounceTopEnter();
        bas_out = new SlideBottomExit();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_report_list, container, false);
        initView(rootView);
        mRcvReportList.setLayoutManager(mLinearLayoutManager);
        mRcvReportList.setHasFixedSize(true);
        mRcvReportList.setAdapter(mReportListAdapter);
        mRcvReportList.setItemAnimator(new DefaultItemAnimator());
        mRcvReportList.setVisibility(View.INVISIBLE);

        setBgaRefreshLayout();
        setListener();
        mBgaRflReport.setIsShowLoadingMoreView(true);
        mBgaRflReport.beginRefreshing();
        return rootView;
    }

    @Override
    public void dealEvent(MainEvent event) {
        //LogUtils.e("Handle Data");
        switch (event.getId()) {
            case Codes.REPORT_DATA_UPLIST:
                if (null != event.getList()) {
                    if (0 == isCollect) {
                        List<Report> temp = new ArrayList<>();
                        temp.clear();
                        temp.addAll(event.getList());
                        data.clear();
                        data.addAll(temp);
                        mRcvReportList.setAdapter(mReportListAdapter);
                        mRcvReportList.setVisibility(View.VISIBLE);
                        mReportListAdapter.notifyDataSetChanged();
                    } else {
                        List<Report> temp = new ArrayList<>();
                        temp.clear();
                        temp.addAll(event.getList());
                        data.clear();
                        for (Report r : temp) {
                            if (r.isCollect()) {
                                data.add(r);
                            }
                        }
                        mRcvReportList.setAdapter(mReportListAdapter);
                        mRcvReportList.setVisibility(View.VISIBLE);
                        mReportListAdapter.notifyDataSetChanged();
                    }
                }
                mBgaRflReport.endRefreshing();
                if (0 == data.size()) {
                    mLnlNullReport.setVisibility(View.VISIBLE);
                } else {
                    mLnlNullReport.setVisibility(View.GONE);
                }
                break;
            case Codes.REPORT_DATA_DOWNLIST:
                if (0 < event.getList().size()) {
                    List<Report> temp = new ArrayList<>();
                    temp.clear();
                    temp.addAll(event.getList());
                    data.addAll(temp);
                    mReportListAdapter.notifyDataSetChanged();
//                    TastyToast.makeText(VCare.get(), getString(R.string.upload_get_more_rpt), TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                } else {
//                    TastyToast.makeText(VCare.get(), getString(R.string.have_no_more_rpt), TastyToast.LENGTH_SHORT, TastyToast.DEFAULT);
                }
                mBgaRflReport.endLoadingMore();
                if (0 == data.size()) {
                    mLnlNullReport.setVisibility(View.VISIBLE);
                } else {
                    mLnlNullReport.setVisibility(View.GONE);
                }
                break;
            case Codes.NET_RPT_DELETE:
                if (event.isSuccess()) {
                    TastyUtils.makeTextShort(R.string.delete_rpt_success, TastyToast.SUCCESS);
                    mReportListAdapter.mReports.removeAll(mReportListAdapter.mDelReportList);
                    mReportListAdapter.mDeleteList.clear();
                    mReportListAdapter.mDelReportList.clear();
                    mReportListAdapter.notifyDataSetChanged();
                    if (0 >= data.size()) {
                        mBgaRflReport.beginRefreshing();
                    }
                } else {
                    mBgaRflReport.beginRefreshing();
                    TastyUtils.makeTextShort(R.string.delete_rpt_failed, TastyToast.ERROR);
                }
                break;
            case Codes.REPORT_BULK_DELETION:
                deleteReports.clear();
                mLlyMenu.animate()
                        .alpha(1.0f)
                        .translationYBy(-mLlyMenu.getHeight())
                        .setDuration(100).start();
                mReportListAdapter.isBulkDeletion = true;
                mRcvReportList.setPadding(0, 0, 0, mLlyMenu.getHeight());
                mReportListAdapter.notifyDataSetChanged();
                break;
            case Codes.REPORT_CANEL_BULK_DELETION:
                mReportListAdapter.isBulkDeletion = false;
                for (Report r :
                        mReportListAdapter.mDelReportList) {
                    r.setChecked(false);
                }
                mReportListAdapter.mDeleteList.clear();
                mReportListAdapter.mDelReportList.clear();
                mLlyMenu.animate()
                        .alpha(0f)
                        .translationYBy(mLlyMenu.getHeight())
                        .setDuration(100).start();
                mRcvReportList.setPadding(0, 0, 0, 0);
                mReportListAdapter.notifyDataSetChanged();
                break;
            // 全部报告
            case Codes.REPORT_GET_ALL:
                isCollect = 0;
                mReportListAdapter.isCollect = 0;
                mTvNullReport.setText(getText(R.string.string_no_report_go_to_measure));
                mBgaRflReport.beginRefreshing();
                break;
            //收藏报告
            case Codes.REPORT_GET_COLLECT:
                isCollect = 1;
                mReportListAdapter.isCollect = 1;
                mTvNullReport.setText(R.string.string_no_collect_report);
                mBgaRflReport.beginRefreshing();
                break;
            case Codes.NET_TIMEOUT:
                TastyToast.makeText(VCare.get(), getString(R.string.bad_netconnect), TastyToast.LENGTH_SHORT, TastyToast.ERROR);
                mBgaRflReport.endRefreshing();
                mBgaRflReport.endLoadingMore();
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (mBgaRflReport != null) {
            mBgaRflReport.postDelayed(() -> {
                if (!hidden) {
                    isCheckAll = false;
                    mReportListAdapter.isBulkDeletion = false;
                    for (Report r :
                            data) {
                        r.setChecked(false);
                    }
                    mReportListAdapter.mDelReportList.clear();
                    mReportListAdapter.mDeleteList.clear();
                    mReportListAdapter.notifyDataSetChanged();
                    if (mLlyMenu.getAlpha() != 0f) {
                        mLlyMenu.animate()
                                .alpha(0f)
                                .translationYBy(mLlyMenu.getHeight())
                                .setDuration(100).start();
                        mRcvReportList.setPadding(0, 0, 0, 0);
                    }
                } else {
                    mBgaRflReport.endRefreshing();
                    mBgaRflReport.endLoadingMore();
                }
            }, 500);
        }
    }

    private void setBgaRefreshLayout() {
        mBgaRflReport.setDelegate(this);
        mBGANormalRefreshViewHolder = new BGANormalRefreshViewHolder(getActivity(), true);
        mBGANormalRefreshViewHolder.setLoadingMoreText(getString(R.string.loading));
        mBGANormalRefreshViewHolder.setPullDownRefreshText(getString(R.string.string_pull_2_refresh));
        mBGANormalRefreshViewHolder.setRefreshingText(getString(R.string.loading));
        mBGANormalRefreshViewHolder.setReleaseRefreshText(getString(R.string.string_release_text));
        mBgaRflReport.setRefreshViewHolder(mBGANormalRefreshViewHolder);
    }

    private void setListener() {

        mTvSelectAll.setOnClickListener(v -> {
            if (isCheckAll) {
                isCheckAll = false;
                for (Report r :
                        data) {
                    r.setChecked(false);
                }
                mReportListAdapter.mDelReportList.clear();
                mReportListAdapter.mDeleteList.clear();
            } else {
                isCheckAll = true;
                mReportListAdapter.mDelReportList.clear();
                mReportListAdapter.mDelReportList.addAll(data);
                for (Report r :
                        data) {
                    mReportListAdapter.mDeleteList.add(r.getId() + "");
                    r.setChecked(true);
                }
            }
            mReportListAdapter.notifyDataSetChanged();
        });

        mTvDeleteAllChecked.setOnClickListener(v -> {
            if (mReportListAdapter.mDeleteList.size() <= 0) {
                TastyUtils.makeTextShort(R.string.string_have_not_choose_report, TastyToast.WARNING);
                return;
            }
            deleteCheckedReport();
        });

        mRcvReportList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = mLinearLayoutManager.findLastVisibleItemPosition();
                // TODO: 2016/11/11 可以在这里判断只渲染当前屏幕中的recyclerview
            }
        });

        mTvNoNetRetry.setOnClickListener(v -> {
            mBgaRflReport.beginRefreshing();
        });
    }

    private void deleteCheckedReport() {
        final NormalDialog dialog = new NormalDialog(getContext());
        dialog.content(getString(R.string.string_delete_report_warm))//
                .style(NormalDialog.STYLE_TWO)//
                .titleTextSize(23)//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();

        dialog.setOnBtnClickL(
                dialog::dismiss,
                () -> {
                    ReportCenter.deleteSome(mReportListAdapter.mDeleteList.toString().replace("[", "").replace("]", "").replaceAll(" ", ""));
                    dialog.dismiss();
                });

    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (NetUtils.noNet()) {
            mBgaRflReport.endRefreshing();
            mRcvReportList.setVisibility(View.GONE);
            mLnlReportNoNet.setVisibility(View.VISIBLE);
            mLnlNullReport.setVisibility(View.INVISIBLE);
            TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
            return;
        } else {
            mLnlReportNoNet.setVisibility(View.GONE);
            mRcvReportList.setVisibility(View.VISIBLE);
        }

        ReportCenter.getNewList("0", 1, Extras.RPT_TYPE_TEMP, 0, isCollect, true);
        LogUtils.d("ReportCenter.getNewList in thread id = " + Thread.currentThread().getId());
        mReportListAdapter.mDelReportList.clear();
        mReportListAdapter.mDeleteList.clear();
//        }
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (NetUtils.noNet()) {
            mBgaRflReport.endLoadingMore();
            mRcvReportList.setVisibility(View.GONE);
            mLnlReportNoNet.setVisibility(View.VISIBLE);
            mLnlNullReport.setVisibility(View.GONE);

            TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
            return false;
        } else {
            mLnlReportNoNet.setVisibility(View.GONE);
            mRcvReportList.setVisibility(View.VISIBLE);
        }

        if (mBgaRflReport.isLoadingMore()) {
            return false;
        }
        if (isCollect == 1) {
            return false;
        }
        DateFormat endFormatter = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        long endTime = data.get(data.size() - 1).getEndtime();
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTimeInMillis(endTime);
        ReportCenter.getNewList(endFormatter.format(endCalendar.getTime()), 1, Extras.RPT_TYPE_TEMP, 1, isCollect, true);
        return true;
    }

    private void initView(View rootView) {
        mRcvReportList = rootView.findViewById(R.id.rcv_report_list);
        mBgaRflReport = rootView.findViewById(R.id.bga_rfl_report);
        mTvDeleteAllChecked = rootView.findViewById(R.id.tv_delete_all_checked);
        mTvSelectAll = rootView.findViewById(R.id.tv_select_all);
        mLlyMenu = rootView.findViewById(R.id.lly_menu);
        mLnlNullReport = rootView.findViewById(R.id.lnl_null_report);
        mTvNullReport = rootView.findViewById(R.id.tv_null_report);
        mTvNoNetRetry = rootView.findViewById(R.id.tv_no_net_retry);
        mLnlReportNoNet = rootView.findViewById(R.id.lnl_report_no_net);
    }
}
